#!/usr/bin/bash

IFS=$'\n'
entrynames=( $(cat 'scripts/cache/entrynames.txt' | fzf --filter="$1" | head -n 10) )
entries=( $(cat 'scripts/cache/entries.txt') )

addedNewActions=false

geticonof() {
  clientclass=''
  clientclass=$1
  iconpath=''
  # Get app icon
  if [ -f "scripts/cache/$clientclass" ]; then
      iconpath=$(cat scripts/cache/$clientclass)
      if [ ! -f "${iconpath}" ]; then # Cache refresh if icon doesnt exist
          iconpath=$(geticons -t "$(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g")" "$clientclass" | head -n 1)
          echo "${iconpath}" > "scripts/cache/$clientclass"
      fi
  else
      iconpath=$(geticons -t "$(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g")" "$clientclass" | head -n 1)
      echo "${iconpath}" > "scripts/cache/$clientclass"
  fi
  if [[ ${iconpath} == "" ]]; then
    # Retry with lowercase if icon not found
    iconpath=$(geticons -t "$(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g")" $(echo "$clientclass" | tr '[:upper:]' '[:lower:]' | sed 's/\ /-/g') | head -n 1)

    if [[ ! ${iconpath} = "" ]]; then
      rm "scripts/cache/$clientclass"
      echo "${iconpath}" > "scripts/cache/$clientclass"
    else 
      newname=$(scripts/iconpatch $clientclass)
      iconpath=$(geticons -t "$(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g")" "$newname" | head -n 1)
      if [[ ! ${iconpath} = "" ]]; then
        rm "scripts/cache/$clientclass"
        echo "${iconpath}" > "scripts/cache/$clientclass"
      else
        # Fallback app icon, replace the path below to the fallback icon of your choice
        # iconpath="/usr/share/icons/Win11-dark/mimes/48/application-x-executable.svg"
        iconpath=$(geticons -t "$(gsettings get org.gnome.desktop.interface icon-theme | sed "s/'//g")" "application-x-executable" | head -n 1)
        rm "scripts/cache/$clientclass"
        echo "${iconpath}" > "scripts/cache/$clientclass"
      fi
    fi
  fi
  echo "$iconpath"
}

quiteSureNotMath() {
  if [[ ${1:0:1} != "0" \
  && ${1:0:1} != "1" \
  && ${1:0:1} != "2" \
  && ${1:0:1} != "3" \
  && ${1:0:1} != "4" \
  && ${1:0:1} != "5" \
  && ${1:0:1} != "6" \
  && ${1:0:1} != "7" \
  && ${1:0:1} != "8" \
  && ${1:0:1} != "9" \
  && ${1:0:1} != "(" \
  && ${1:0:1} != ")" \
  ]]; then
    echo 'true'
  else
    echo 'false'
  fi
}

# Search inits: math
if [[ "$1" == "--calculator" ]]; then
  echo -n '[{"name":"Calculator - Type something!","icon":"images/svg/dark/calculator.svg","exec":"wl-copy \"Clipboard contents ;)\""}]'
  eww update winsearch_actions='{"name":"Calculator - Type something!","icon":"images/svg/dark/calculator.svg","exec":"wl-copy \"Clipboard contents ;)\""}'
  eww update winsearch_actions_type='Math result'
  addedNewActions=true
  exit 0
fi

# Quick commands
if [[ "$1" == ">"* ]]; then
  cd ~/.config/eww 
  if [[ "$1" == ">load"* ]]; then
    searching=$(echo "$1" | sed 's/>load //g'  | sed 's/>load//g')
    profilenames=( $(ls css/savedcolors/ | grep .txt | sed 's/_iconcolor_//g' | sed 's/.txt//g' | fzf --filter="$searching") )
    echo -n '['
    for x in "${!profilenames[@]}"; do
      if [ "$x" != "0" ]; then
        printf ','
      fi
      profilejson='{"name": "'"${profilenames[x]}"'", "exec": ">load '"${profilenames[x]}"'"}'
      if (( x == 0 )); then
        eww update winsearch_actions="$profilejson"
        eww update winsearch_actions_type='Color theme'
        addedNewActions=true
      fi

      echo -n "$profilejson"
    done
    echo -n ']'
  else
    echo '[]'
  fi
  exit 0
fi

# Do math
if [[ $(quiteSureNotMath "$1") == "false" ]]; then
  mathAns=$(qalc $1 | head -n 1)
  mathAns="${mathAns#*= }"
  mathAns="${mathAns#*≈ }"
  if [[ "$mathAns" == *"error"* || "$mathAns" == *"warning"* ]]; then
    echo '[{"name":"Invalid math","icon":"images/svg/dark/calculator.svg","exec":"wl-copy \"Clipboard contents ;)\""}]'
    exit 0
  else
    ansjson='{"name": "'"$mathAns"'","icon":"images/svg/dark/calculator.svg","exec": "wl-copy \"'"$mathAns"'\""}'
    eww update winsearch_actions="$ansjson"
    eww update winsearch_actions_type='Math result'
    addedNewActions=true
    echo '['"$ansjson"']'
  fi
  exit 0
fi

# Application search
printf '['

for x in "${!entrynames[@]}"; do
  if [ "$x" != "0" ]; then
    printf ','
  fi
  appjson=$(echo $entries | gojq -c -M '."'"${entrynames[x]}"'"')
  if (( x == 0 )); then
    eww update winsearch_actions="$appjson"
    eww update winsearch_actions_type='Application'
    addedNewActions=true
  fi
  # iconname=$(echo "$appjson" | gojq -r -c -M '.icon')
  # appjson=$(echo "$appjson" | gojq '.icon = "'$(geticonof "$iconname")'"')
  echo -n "$appjson"
done

printf ']'

if [[ "$addedNewActions" == "false" ]]; then
  eww update winsearch_actions='{"name":"'"$1"'","icon":"images/svg/dark/protocol.svg","exec":"wl-copy \"Clipboard contents ;)\""}'
  eww update winsearch_actions_type='Run command'
fi